% plot_convergence_from_csv.m
% Plot optimization convergence from CSV data
function plot_convergence_from_csv(csv_file, output_dir, case_name)
    % Read CSV data
    data = readtable(csv_file);
    
    if isempty(data)
        warning('No convergence data found');
        return;
    end
    
    % Create figure
    fig = figure('Name', 'Optimization Convergence', 'Position', [100, 100, 1000, 600]);
    tiledlayout(2, 2);
    
    % Plot 1: Best Time over iterations
    ax1 = nexttile;
    plot(ax1, data.iteration, data.best_time, 'b-o', 'LineWidth', 1.5, 'MarkerSize', 4);
    title('Best Time Convergence');
    xlabel('Iteration');
    ylabel('Best Time');
    grid on;
    
    % Plot 2: Best Spill over iterations
    ax2 = nexttile;
    plot(ax2, data.iteration, data.best_spill, 'r-s', 'LineWidth', 1.5, 'MarkerSize', 4);
    title('Best Spill Convergence');
    xlabel('Iteration');
    ylabel('Best Spill');
    grid on;
    
    % Plot 3: Population Diversity
    ax3 = nexttile;
    plot(ax3, data.iteration, data.population_diversity, 'g-^', 'LineWidth', 1.5, 'MarkerSize', 4);
    title('Population Diversity');
    xlabel('Iteration');
    ylabel('Diversity');
    grid on;
    
    % Plot 4: Combined Time vs Spill progression
    ax4 = nexttile;
    yyaxis left;
    plot(ax4, data.iteration, data.best_time, 'b-', 'LineWidth', 1.5);
    ylabel('Best Time', 'Color', 'b');
    yyaxis right;
    plot(ax4, data.iteration, data.best_spill, 'r-', 'LineWidth', 1.5);
    ylabel('Best Spill', 'Color', 'r');
    title('Time vs Spill Progression');
    xlabel('Iteration');
    grid on;
    
    % Save figure
    filename = sprintf('%s_convergence.png', case_name);
    filepath = fullfile(output_dir, filename);
    saveas(fig, filepath);
    
    % Also save as .fig for interactive use
    fig_filepath = fullfile(output_dir, sprintf('%s_convergence.fig', case_name));
    saveas(fig, fig_filepath);
    
    fprintf('  Convergence plot saved: %s\n', filepath);
    close(fig);
end



